package myJs.cps

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import myJs.myPkg.DatepickerOptions
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.html.Input
import myJs.myPkg.Hooks._
import myJs.Implicits._
import org.scalajs.dom.Event

import scala.scalajs.js

/** Created by yz on 15/9/2023
  */
object PureDatePickerCp {

  case class Props(placeHolder: String = "", name: String = "", onChangeF: String => Callback, value: String) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val inputRef = Ref[Input]

    useEffect(
      {
        val options = DatepickerOptions(format = Tool.pattern, autoclose = true, forceParse = true, language = "zh-CN")
        inputRef.foreach{y=>
          $(y).datepicker(options)
        }
      },
      List()
    )

    useEffect(
      {
        inputRef
          .foreach { y =>
            $(y).myOffThenOn(
              "changeDate",
              (e: Event) => {
                val myV = e.target.asInstanceOf[Input].value
                props.onChangeF(myV)
              }
            )
          }
          .map { x =>
            inputRef.foreach { y =>
              $(y).off("changeDate")
            }
          }
      },
      List()
    )

    useEffect(
      {
        inputRef.foreach { y =>
          $(y).datepicker("update", props.value)
        }
      },
      List(props.value)
    )

    input(
      `type` := "text",
      className := "filterInput form-control startTime",
      name := props.name,
      width := "100%",
      placeholder := props.placeHolder,
      readOnly := true,
      value := props.value
    ).withRef(inputRef)

  }

}
